# -*- coding: utf-8 -*-
from five import grok
from zope import schema
from plone.directives import form
from zope.interface import Invalid
from plone.app.textfield import RichText
from z3c.relationfield.schema import RelationList, RelationChoice
from plone.formwidget.contenttree import ObjPathSourceBinder,ContentTreeFieldWidget

from Products.bpContents import _

from plone.formwidget.autocomplete import AutocompleteFieldWidget
from collective.z3cform.widgets.token_input_widget import TokenInputFieldWidget
from plone.namedfile.field import NamedBlobImage
from Products.ATContentTypes.interface.image import IATImage
from plone.indexer import indexer

from plone.formwidget.autocomplete import AutocompleteFieldWidget
from plone.formwidget.autocomplete import AutocompleteMultiFieldWidget
from Products.bpContents.categoriasVocab import CategoriasVocab
from zope.interface import Interface, implements
from z3c.formwidget.query.interfaces import IQuerySource
from zope.schema.interfaces import IContextSourceBinder
from Products.CMFCore.utils import getToolByName
from zope.schema.vocabulary import SimpleVocabulary,SimpleTerm
from Products.bpContents.adapter import KeywordSourceBinder


class ILibro(form.Schema):
    """Una reseña de libro
    """

    cuerpo = RichText(
        title=_(u"Cuerpo"),
        description=_(u"Texto principal"),
    )

    relaciones = RelationList(
        title=_(u"Documentos Relacionados"),
        description=_(u"Otros articulos o galerias que complementen el documento actual"),
        value_type=RelationChoice(
            source=ObjPathSourceBinder(

            ),
        ),
        required=False,
    )

    portada = NamedBlobImage(
        title=_(u"Portada del libro"),
        required=False,
    )

    form.widget(categorias=AutocompleteMultiFieldWidget)
    #categorias =schema.Choice(title=u"Categorias",source=KeywordSourceBinder())
    categorias = schema.List(title=u"Tematicas",value_type=schema.Choice(title=u"Categorias",source=KeywordSourceBinder()),required=False)


@indexer(ILibro)
def startIndexer(context):
    if context.portada is None:
       return None
    return context.portada

@indexer(ILibro)
def startIndexerA(context):
    if context.categorias is None:
        return None

    atvm = getToolByName(context , 'portal_vocabularies')
    engines = atvm.getVocabularyByName('categorias_vocab')
    result=[]

    for clave in context.categorias:
        result.append(clave.split(":")[0])
    return result

grok.global_adapter(startIndexerA, name="articuloCategoria")
grok.global_adapter(startIndexer, name="portadaLibro")

from plone.directives.dexterity import DisplayForm
from Products.bpContents.BaseClassView import BaseClassView
class View(DisplayForm,BaseClassView):
    grok.context(ILibro)
    grok.require('zope2.View')

    def getCategoria(self):
        """Devuelve solo el título de las categorias"""
        context=self.context
        if len(context.categorias)>0:
            r=[]
            for cate in context.categorias:
                if len(cate.split(":"))==1:
                    cate=":"+cate
                r.append(cate)
            return r
        else:
            return None

    def tieneImagenes(self):
        """Defuelve true si conteien imágenes"""

        if self.context.portada==None:
            return False
        else:
            return True